package com.example.cheeseerpadmin.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cheeseerpadmin.sys.common.DataGridView;
import com.example.cheeseerpadmin.sys.common.ResultObj;
import com.example.cheeseerpadmin.sys.entity.SysLoginfo;
import com.example.cheeseerpadmin.sys.service.SysLoginfoService;
import com.example.cheeseerpadmin.sys.vo.LoginfoVo;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/loginfo")
public class LoginfoController {

    @Autowired
    public SysLoginfoService sysLoginfoService;

    //查询登录日志数据，如果前端没有传递查询条件，那么他就会使用默认条件进行查询得到全部数据并进行展示。
    //而如果它得到了查询的条件，那么他就会按照查询的条件进行查询。
    @RequestMapping("/loadAllLoginfo")
    public DataGridView loadAllLoginfo(LoginfoVo loginfoVo) {
        Page<SysLoginfo> page = new Page<>(loginfoVo.getPage(), loginfoVo.getLimit());
        QueryWrapper<SysLoginfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(loginfoVo.getLoginname()), "loginname", loginfoVo.getLoginname());
        queryWrapper.like(StringUtils.isNotBlank(loginfoVo.getLoginip()), "loginip", loginfoVo.getLoginip());
        queryWrapper.ge(loginfoVo.getStartDate() != null, "logintime", loginfoVo.getStartDate());
        queryWrapper.le(loginfoVo.getEndDate() != null, "logintime", loginfoVo.getEndDate());
        queryWrapper.orderByDesc("logintime");
        Page<SysLoginfo> page1 = sysLoginfoService.page(page, queryWrapper);
        return new DataGridView(page1.getTotal(), page1.getRecords());
    }

    //删除
    @RequestMapping("/deleteLoginfoById")
    public ResultObj deleteLoginById(Integer id) {
        try {
            sysLoginfoService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    //批量删除
    @RequestMapping("/batchDeleteLoginfo")
    public ResultObj deleteLoginfoByIds(LoginfoVo loginfoVo) {
        try {
            Collection<Serializable> idList = new ArrayList<>();
            for (Integer id : loginfoVo.getIds()) {
                idList.add(id);
            }
            sysLoginfoService.removeByIds(idList);
            return ResultObj.DELETE_SUCCESS;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }
}
